package cn.itcast.goods.cart.web.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itcast.goods.book.domain.Book;
import cn.itcast.goods.cart.domain.CartItem;
import cn.itcast.goods.cart.service.CartItemService;
import cn.itcast.goods.user.domain.User;
import cn.mytools.servlet.BaseServlet;

public class CartItemServlet extends BaseServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4379299447021633293L;
	private CartItemService cartItemService = new CartItemService();

	public String myCart(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		User user = (User) req.getSession().getAttribute("sessionUser");
		String uid = user.getUid();
		List<CartItem> cartItemList = cartItemService.findByUid(uid);
		req.setAttribute("cartItemList", cartItemList);
		return "f:/jsps/cart/list.jsp";
	}

	public String addCartItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String quantity = req.getParameter("quantity");

		String bid = req.getParameter("bid");
		Book book = new Book();
		book.setBid(bid);

		User user = (User) req.getSession().getAttribute("sessionUser");

		CartItem cartItem = new CartItem();
		cartItem.setQuantity(Integer.parseInt(quantity));
		cartItem.setBook(book);
		cartItem.setUser(user);

		cartItemService.addCartItem(cartItem);
		return myCart(req, resp);
	}

	public String batchDeleteCartItem(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String cartItemIds = req.getParameter("cartItemIds");
		cartItemService.batchDeleteCartItem(cartItemIds);
		return myCart(req, resp);
	}

	public String updateQuantity(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String cartItemId = req.getParameter("cartItemId");
		int quantity = Integer.parseInt(req.getParameter("quantity"));
		CartItem cartItem = cartItemService.updateQuantity(cartItemId, quantity);
		StringBuilder sb = new StringBuilder("{");
		sb.append("\"quantity\":").append(cartItem.getQuantity());
		sb.append(",\"subtotal\":").append(cartItem.getSubtotal());
		sb.append("}");
		resp.getWriter().print(sb);
		return null;
	}

	public String loadCartItems(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String cartItemIds = req.getParameter("cartItemIds");
		List<CartItem> cartItemList = cartItemService.loadCartItems(cartItemIds);
		req.setAttribute("cartItemList", cartItemList);
		req.setAttribute("cartItemIds", cartItemIds);

		return "f:/jsps/cart/showitem.jsp";
	}

}
